
package cn.ibizlab.eam.core.extensions.service;

import cn.ibizlab.eam.core.eam_core.domain.*;
import cn.ibizlab.eam.core.eam_core.filter.EMItemTradeSearchContext;
import cn.ibizlab.eam.core.eam_core.filter.EMStockSearchContext;
import cn.ibizlab.eam.core.eam_core.service.IEMItemTradeService;
import cn.ibizlab.eam.core.eam_core.service.IEMStockService;
import cn.ibizlab.eam.core.eam_core.service.IEMWPListService;
import cn.ibizlab.eam.core.eam_core.service.impl.EMItemRInServiceImpl;
import cn.ibizlab.eam.core.util.helper.Aops;
import cn.ibizlab.eam.util.dict.StaticDict;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.context.annotation.Primary;

import java.math.RoundingMode;
import java.util.*;

/**
 * 实体[入库单] 自定义服务对象
 */
@Slf4j
@Primary
@Service("EMItemRInExService")
public class EMItemRInExService extends EMItemRInServiceImpl {

    @Autowired
    private IEMStockService emstockService;

    @Autowired
    private IEMItemTradeService iemItemTradeService;

    @Autowired
    private IEMWPListService iemwpListService;


    @Override
    protected Class currentModelClass() {
        return com.baomidou.mybatisplus.core.toolkit.ReflectionKit.getSuperClassGenericType(this.getClass().getSuperclass(), 1);
    }

    /**
     * 自定义行为[Confirm]用户扩展
     *
     * @param et
     * @return
     */
    @Override
    @Transactional
    public EMItemRIn confirm(EMItemRIn et) {
        // 库存的修改
        // 根据入库单号找到入库单所有信息
        et = this.get(et.getEmitemrinid());
        // 首先根据物品id,仓库id,库位id以及批次在库存表里面查找有没有该物品的库存记录
        String itemId = et.getItemid(); // 物品id
        String storeId = et.getStoreid();// 仓库id
        String storePartId = et.getStorepartid(); // 库位id
        String batCode = et.getBatcode(); // 批次

        EMStockSearchContext ctx = new EMStockSearchContext();
        ctx.setN_itemid_eq(itemId);
        ctx.setN_storeid_eq(storeId);
        ctx.setN_storepartid_eq(storePartId);
        ctx.setN_batcode_eq(batCode);
        List<EMStock> emStocks = emstockService.searchDefault(ctx).getContent();
        // 若找到该物品相关记录，进行仓库，库位，批次判断
        // 若没找到则向库存表中插入一条该物品的库存记录
        if(emStocks.size()>0) {
            EMStock emStock = emStocks.get(0);
            emStock.setStockcnt(et.getPsum() + emStock.getStockcnt());
            emstockService.update(emStock);
        }else{
            EMStock stock = new EMStock();
            stock.setItemid(itemId);
            stock.setStoreid(storeId);
            stock.setStorepartid(storePartId);
            stock.setBatcode(batCode); //批次
            stock.setStockcnt(et.getPsum()); //库存数量
            stock.setOrgid(et.getOrgid()); //组织
            emstockService.create(stock);
        }

        // 更新物品
        EMItem emItem = new EMItem();
        EMItem currentEmItem = emitemService.get(et.getItemid());
        if (currentEmItem.getStocksum() == null) {
            currentEmItem.setStocksum(0.0);
        }
        if (currentEmItem.getAmount() == null) {
            currentEmItem.setAmount(0.0);
        }
        // 库存量=原有库存数+当前新增
        emItem.setStocksum(currentEmItem.getStocksum() + et.getPsum());
        // 库存金额=原有库存金额+当前新增库存金额
        emItem.setAmount(currentEmItem.getAmount() + et.getAmount());
        // 如果当前物品库存量发生变化,需要计算平均价 平均价=库存金额/库存量
        if (emItem.getStocksum() > 0) {
            emItem.setPrice(NumberUtils.toScaledBigDecimal(emItem.getAmount() / emItem.getStocksum(), 2, RoundingMode.HALF_UP).doubleValue());
        }
        emItem.setStoreid(et.getStoreid());
        emItem.setStorepartid(et.getStorepartid());
        // 重新计算平均税费 平均税费=总税费/总数量
        EMItemTradeSearchContext tradeCtx = new EMItemTradeSearchContext();
        tradeCtx.setN_itemid_eq(et.getItemid());
        tradeCtx.setN_shf_gt(0.0);
        List<EMItemTrade> emItemTrades = iemItemTradeService.searchDefault(tradeCtx).getContent();
        // 总税费
        double shfAmount = emItemTrades.stream().mapToDouble(EMItemTrade::getShf).sum();
        // 总数量
        double shfSum = emItemTrades.stream().mapToDouble(EMItemTrade::getPsum).sum();
        if (shfSum > 0) {
            emItem.setShfprice(NumberUtils.toScaledBigDecimal(shfAmount / shfSum, 2, RoundingMode.HALF_UP).doubleValue());
        }

        // 最后入料时间
        EMItemTrade emItemTrade = iemItemTradeService.get(et.getEmitemrinid());
        if (emItemTrade.getInoutflag() != null && emItemTrade.getInoutflag() == 1) {
            emItem.setLastindate(emItemTrade.getSdate());
        }
        // 最新请购人
        if (emItemTrade.getInoutflag() != null && emItemTrade.getInoutflag() == 1) {
            emItem.setLastaempid(emItemTrade.getAempid());
        }
        emitemService.update(emItem);

        // 入库单确认后，流程步骤WFSTEP置空
        et.setWfstep(null);
        // 入库状态设置为20（20:已入库）
        et.setRinstate(StaticDict.EMRINSTATE.ITEM_20.getValue());
        Aops.getSelf(this).update(et);

        // 修改采购申请的状态(30:已完成)
        EMPODetail empoDetail = empodetailService.get(et.getPodetailid());
        EMWPList emwpList = iemwpListService.get(empoDetail.getWplistid());
        emwpList.setWpliststate(StaticDict.EMWPLISTSTATE.ITEM_30.getValue());
        iemwpListService.update(emwpList);

        return super.confirm(et);
    }
}

